package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;

import mail.Mail;
import mail.MyModelEmail;
import tools.OptionReader;
import calendar.CheckboxCalendar;

/**
 * Klasse erzeugt Fenster zum Aufgaben anlegen
 * 
 * @author Michi
 * 
 */
public class NewTaskWindow extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5468339036211170202L;

	private Connection connection = null;

	// Textfelder fuer Detailangaben zu jeweiligen Tasks
	private JTextField textField;
	@SuppressWarnings("unused")
	private JTextField textField_1;
	@SuppressWarnings("unused")
	private JTextField textField_2;
	private JTextField textField_3;
	private Statement stat = null;
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;

	private LinkedList<CheckboxCalendar> cals = new LinkedList<CheckboxCalendar>();
	private String[] calDropdown;
	private JComboBox priority = new JComboBox();
	private JComboBox kalender;
	private JTextArea textArea;
	private LinkedList<String> emailLinkedList;

	private JFrame temp;

	@SuppressWarnings("rawtypes")
	private LinkedList participants = new LinkedList();

	private int idtask = 0;

	// public static void main(String[] args) {
	// EventQueue.invokeLater(new Runnable() {
	// public void run() {
	// try {
	// JFrame frame = new JFrame(new NewTaskWindow());
	// frame.setVisible(true);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	// });
	// }

	int speak = 0;
	String[] fenstertitel = { "Aufgabe hinzufügen", "Add Task", "Add Negotium" };

	String[] titel = { "Titel", "heading", "vocabulum" };
	String[] abgabe = { "Abgabedatum", "deadline", "spatium" };
	String[] prior = { "Priorität", "priority", "interest" };
	String[] teilnehmer = { "Teilnehmer", "participants", "auditor" };
	String[] kalendar = { "Kalender", "calendar", " calendarium" };
	String[] beschreibung = { "Beschreibung", "description", "explicatio" };

	String[] button = { "Hinzufügen", "Add", "Addere" };

	String[] prioHoch = { "hoch", "high", "altus" };
	String[] prioMittel = { "mittel", "medium", "medium" };
	String[] prioTief = { "niedrig", "low", "penitus" };

	@SuppressWarnings("deprecation")
	public NewTaskWindow(final Object tdp) {

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		speak = Integer.parseInt(or.getLanguage());

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		Dimension size = new Dimension(600, 500);
		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();

		}
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet party = stat
					.executeQuery("SELECT idTask FROM `sopra-ws12-awesome_fireballs`.`Task`ORDER BY idTask DESC LIMIT 1;");

			while (party.next()) {
				idtask = party.getInt(1) + 1;
			}

			ResultSet idsCalendar = stat
					.executeQuery("SELECT idCalendar, name, idCreator FROM Calendar WHERE idUser = "
							+ Test.iduser + ";");

			while (idsCalendar.next()) {
				CheckboxCalendar temp = new CheckboxCalendar(
						idsCalendar.getInt("idCalendar"),
						idsCalendar.getString("name"),
						idsCalendar.getInt("idCreator"));
				cals.add(temp);
			}

			calDropdown = new String[cals.size()];
			for (int i = 0; i < cals.size(); i++) {
				calDropdown[i] = cals.get(i).getName();
			}

		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		setTitle(fenstertitel[speak]);
		getContentPane().setBackground(Color.LIGHT_GRAY);
		getContentPane().setLayout(new BorderLayout(0, 0));

		// Rechts Panel, welches Detailansicht enthaelt
		JPanel centerpanel = new JPanel();
		centerpanel.setBackground(new Color(r, g, b));
		getContentPane().add(centerpanel, BorderLayout.CENTER);
		centerpanel.setLayout(null);

		// Erstellen der Label zu jeweiligen Textfeldern
		JLabel lblName = new JLabel(titel[speak]);
		lblName.setHorizontalAlignment(SwingConstants.RIGHT);
		lblName.setBounds(50, 30, 97, 16);
		centerpanel.add(lblName);

		JLabel lblStrae = new JLabel(abgabe[speak]);
		lblStrae.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStrae.setBounds(50, 58, 97, 16);
		centerpanel.add(lblStrae);

		JLabel lblPlz = new JLabel(prior[speak]);
		lblPlz.setHorizontalAlignment(SwingConstants.RIGHT);
		lblPlz.setBounds(50, 86, 97, 16);
		centerpanel.add(lblPlz);

		JLabel lblStadt = new JLabel(teilnehmer[speak]);
		lblStadt.setHorizontalAlignment(SwingConstants.RIGHT);
		lblStadt.setBounds(50, 114, 97, 16);
		centerpanel.add(lblStadt);

		JLabel lblKalendar = new JLabel(kalendar[speak]);
		lblKalendar.setHorizontalAlignment(SwingConstants.RIGHT);
		lblKalendar.setBounds(50, 142, 97, 16);
		centerpanel.add(lblKalendar);

		JLabel lblEmail = new JLabel(beschreibung[speak]);
		lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
		lblEmail.setBounds(50, 170, 97, 16);
		centerpanel.add(lblEmail);

		// Erstellen der Textfelder

		// Titel
		textField = new JTextField();
		textField.setBounds(180, 24, 344, 28);
		centerpanel.add(textField);
		textField.setColumns(10);

		// Datum

		// Jahr //

		Date d = new Date();
		int y = d.getYear() + 1900;
		int m = d.getMonth() + 1;
		int t = d.getDate();

		String[] jahreArray = new String[30];

		int jz = y;
		for (int i = 0; i < 30; i++) {
			jahreArray[i] = Integer.toString(jz);
			jz++;
		}

		final JComboBox jahr = new JComboBox(jahreArray);
		jahr.setSelectedIndex(y - 2013);
		// !
		jahr.setBounds(330, 56, 85, 20);
		centerpanel.add(jahr);

		// Monat //

		String[] monatsArray = new String[12];

		for (int i = 0; i < 12; i++) {
			String s = "";
			if (i < 9) {
				s = "0";
			}
			s += Integer.toString(i + 1);
			monatsArray[i] = s;
		}

		final JComboBox monat = new JComboBox(monatsArray);
		monat.setSelectedIndex(m - 1);

		monat.setBounds(255, 56, 70, 20);
		centerpanel.add(monat);

		// Tag //

		String[] tagesArray = new String[31];

		for (int i = 0; i < 31; i++) {
			String s = "";
			if (i < 9) {
				s = "0";
			}
			s += Integer.toString(i + 1);
			tagesArray[i] = s;
		}

		final JComboBox tag = new JComboBox(tagesArray);
		tag.setSelectedIndex(t - 1);

		tag.setBounds(180, 56, 70, 20);
		centerpanel.add(tag);

		// textField_1 = new JTextField();
		// textField_1.setBounds(180, 52, 344, 28);
		// centerpanel.add(textField_1);
		// textField_1.setColumns(10);

		// Prioritaet

		// textField_2 = new JTextField();
		// textField_2.setColumns(10);
		// textField_2.setBounds(180, 80, 344, 28);
		// centerpanel.add(textField_2);

		// Setzt und Erstellt Priority auswahl checkbox

		priority.removeAllItems();

		String[] priorityvalues = { prioTief[speak], prioMittel[speak],
				prioHoch[speak] };
		for (String s : priorityvalues) {
			priority.addItem(s);
		}

		priority.setSelectedIndex(1);
		priority.setBounds(180, 80, 344, 28);
		centerpanel.add(priority);

		// Teilnehmer
		textField_3 = new JTextField();
		textField_3.setColumns(10);
		textField_3.setBounds(180, 108, 309, 28);
		centerpanel.add(textField_3);

		// Kalender
		kalender = new JComboBox(calDropdown);

		kalender.setBounds(180, 142, 344, 28);

		centerpanel.add(kalender);

		// Details
		textArea = new JTextArea();
		textArea.setBounds(180, 170, 344, 250);
		centerpanel.add(textArea);

		// Erstellen der Buttons
		JButton btnSpeichern = new JButton(button[speak]);
		btnSpeichern.setBounds(366, 431, 158, 29);
		centerpanel.add(btnSpeichern);

		JButton btnAddParticipants = new JButton("+");
		btnAddParticipants.setBounds(491, 109, 33, 27);

		temp = this;

		btnAddParticipants.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				JFrame addcontact = new AddContactWindow(temp, false);
				addcontact.setVisible(true);

			}
		});

		centerpanel.add(btnAddParticipants);

		// ActionListener um Kontakt Hinzuzuf�gen

		ActionListener bu = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {

				@SuppressWarnings("rawtypes")
				SwingWorker worker = new SwingWorker() {

					@Override
					public Object doInBackground() {

						try {
							Class.forName("com.mysql.jdbc.Driver");
							connection = DriverManager
									.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
						} catch (ClassNotFoundException e) {

							e.printStackTrace();
						} catch (SQLException e) {

							e.printStackTrace();
							return false;
						}

						Statement stat = null;

						// //////// Date auslesen //////////

						int aY = Integer.parseInt((String) jahr
								.getSelectedItem());
						int aM = monat.getSelectedIndex() + 1;
						int aD = tag.getSelectedIndex() + 1;

						// Prüft ob der Monat so viele Tage hat.
						if (aD > monthLength(new Date(aY - 1900, aM - 1, 1))) {

							new NotifyFrame(
									"Dieser Monat besitzt diesen Tag nicht.")
									.setVisible(true);
						}

						else {
							Date setDate = makeDate(aY, aM, aD);
							Date todayDate = new Date();
							// Tag muss um eins gesenkt werden.
							int yT = todayDate.getYear();
							int mT = todayDate.getMonth();
							int dT = todayDate.getDate();
							if (dT == 1 && mT == 0) {
								yT--;
								mT = 11;
								dT = 31;
							} else if (dT == 1) {
								mT--;
								yT = monthLength(new Date(yT, mT, 1));
							} else {
								dT--;
							}
							todayDate = makeDate(yT, mT, dT);

							// Prüft ob die Deadline in der Zukunft liegt
							if (setDate.before(todayDate)) {
								new NotifyFrame(
										"Die Deadline liegt in der Vergangenheit.")
										.setVisible(true);
							} else {

								try {

									stat = connection.createStatement();

									String name = textField.getText();
									// String prioritaet =
									// textField_2.getText();

									String prioritaet = "1";

									if (priority.getSelectedIndex() == 0) {
										prioritaet = "0";

									} else if (priority.getSelectedIndex() == 2) {
										prioritaet = "2";

									}

									String description = textArea.getText();

									// Formt das Date in einen korrekten String.
									SimpleDateFormat sdf = new SimpleDateFormat(
											"yyyy-MM-dd HH:mm:ss");

									StringBuilder sB = new StringBuilder(
											sdf.format(setDate));
									String setString = sB.toString();
									//

									stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

									ResultSet party = stat
											.executeQuery("SELECT idTask FROM `sopra-ws12-awesome_fireballs`.`Task`ORDER BY idTask DESC LIMIT 1;");

									int idTask = 0;
									while (party.next()) {
										idTask = party.getInt(1) + 1;
									}

									int selectedCal = kalender
											.getSelectedIndex();
									int idSelectedCal = cals.get(selectedCal)
											.getIdCalendar();

									// ResultSet todo = stat
									// .executeQuery("SELECT idToDo FROM `sopra-ws12-awesome_fireballs`.ToDo ORDER BY idToDo DESC LIMIT 1;");
									// int idToDo = 0;
									// while (todo.next()) {
									// idToDo = todo.getInt(1) + 1;
									// }

									connection.setAutoCommit(false);
									PreparedStatement pstmt = connection
											.prepareStatement("INSERT INTO Task VALUES(?, ?, ?, ?, ?, ?, ?)");

									pstmt.setInt(1, idTask);
									pstmt.setInt(2, idSelectedCal);
									pstmt.setString(3, name);
									pstmt.setString(4, setString);
									pstmt.setString(5, prioritaet);
									pstmt.setString(6, description);
									pstmt.setInt(7, 0);

									System.out.println(pstmt.toString());

									ResultSet nextparticipantid = stat
											.executeQuery("SELECT idparticipantsToDo FROM `sopra-ws12-awesome_fireballs`.participantsToDo ORDER BY idparticipantsToDo DESC LIMIT 1;");
									int nextpartid = 0;
									while (nextparticipantid.next()) {
										nextpartid = nextparticipantid
												.getInt(1) + 1;
									}
									// ppstmt = Prepared Participants STateMenT
									PreparedStatement ppstmt = connection
											.prepareStatement("INSERT INTO `sopra-ws12-awesome_fireballs`.participantsToDo VALUES(?, ?, ?)");
									System.out.println(participants.size());
									for (int i = 0; i < participants.size(); i++) {
										ppstmt.setInt(1, nextpartid + i);
										ppstmt.setInt(2, idTask);
										ppstmt.setString(3,
												(String) participants.get(i));
										ppstmt.addBatch();

										System.out.println(nextpartid);
										System.out.println(ppstmt.toString());

									}

									pstmt.addBatch();
									

									pstmt.executeBatch();
									ppstmt.executeBatch();

									connection.commit();
									connection.setAutoCommit(true);

									
								} catch (SQLException e) {
									e.printStackTrace();
								}
								return stat;

							}

						}
						return null;
					}

					@Override
					public void done() {

						if (emailLinkedList != null) {
							if (emailLinkedList.size() > 0) {
								Mail temp = new Mail();

								temp.setTo(emailLinkedList);

								temp.setBetreff("Einladung zu Aufgabe: "
										+ textField.getText());

								temp.setText(idtask + "");

								MyModelEmail mme = new MyModelEmail();
								mme.sendMail(temp, true);
							}
						}
						if (tdp != null && tdp instanceof ToDoPane) {
							((ToDoPane) tdp).update();
							((ToDoPane) tdp).setListselectionactivated(true);
						}
						dispose();

					}

				};

				worker.execute();

			}

		};

		btnSpeichern.addActionListener(bu);

	}

	/**
	 * Erzeugt Date aus Int
	 * 
	 * @param year
	 *            Jahr
	 * @param month
	 *            Monat
	 * @param day
	 *            Tag
	 * @return Gibt Datum zurück
	 */
	@SuppressWarnings("deprecation")
	public static Date makeDate(int year, int month, int day) {

		return new Date(year - 1900, month - 1, day);

	}

	// Ermittelt Laenge des Monats.

	/**
	 * Gibt Länge des Monats zurück
	 * 
	 * @param d
	 *            Datum des Monats dessen Länge gewollt wird
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static int monthLength(Date d) {

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, d.getYear());
		cal.set(Calendar.MONTH, d.getMonth());
		cal.set(Calendar.DATE, d.getDate());

		return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

	@SuppressWarnings("rawtypes")
	public void setParticipants(LinkedList ll) {
		this.participants = ll;
	}

	public int getIdTask() {
		return idtask;
	}

	/**
	 * Setzt Teilnehmer
	 */
	public void setParticipantsText() {
		emailLinkedList = new LinkedList<String>();
		String mail = "";
		String s = "";
		Statement stat;
		try {
			stat = connection.createStatement();

			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			for (int i = 0; i < participants.size(); i++) {
				ResultSet rs = stat
						.executeQuery("SELECT Adress.* FROM Adress WHERE idAdress= "
								+ participants.get(i) + ";");
				rs.next();
				s += rs.getString("fname") + " ";
				s += rs.getString("lname") + ", ";
				mail = rs.getString("email");
				emailLinkedList.add(mail);

			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		textField_3.setText(s);
	}

}
